<?php
class HomeController extends Controller {
	
	public $result = array();
	
	public function actions() {
		return array();
	}
	
	public function actionIndex() {
		$data = array();
		$this->render('index', $data);
	}
	
	public function actionCrawler() {
		$url   = isset($_GET['url']) ? $_GET['url'] : null; 
		$depth = isset($_GET['depth']) ? $_GET['depth'] : null;
		
		if( ! $url) {
			throw new CHttpException(400, 'Url is not null');
		}
		
		if( ! $depth) {
			throw new CHttpException(400, 'Depth is not null');
		}
		
		$this->crawl($url, $depth);
		
		Dumper::dump($this->result);
		
		die();
	}
	
	public function crawl($url, $depth = 5) {
		$href = null;
		
		if($depth == 0 || $url == null) {
			return;
		}
		
		$result = @file_get_contents($url);
		
		if( $result ) {
	
			$pattern = "/<a[\s]+[^>]*?href[\s]?=[\s\"\']+"."(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/";
	
			preg_match_all($pattern, strip_tags($result, "<a>"), $matches, PREG_SET_ORDER );
	
			foreach($matches as $match) {
				$href = $match[1];
	
				if($href == '/') {
					continue;
				}
	
				if(0 !== strpos($href, 'http')) {
					$href = $url . $match[1];
				}
	
				
				if( ! in_array($href, $this->result))
				{
				echo $href;
					array_push($this->result, '<a href="'. $href .'">' . $href . '</a>');
						
					$this->crawl($href, $depth - 1);
				}
			}
		}
	}
	
}